package com.gibs.peixunapi.service.impl;

import com.gibs.peixunapi.VO.StudyRecordVO;
import com.gibs.peixunapi.dao.*;
import com.gibs.peixunapi.enums.ResultEnum;
import com.gibs.peixunapi.excepiton.BaseException;
import com.gibs.peixunapi.model.Exercises;
import com.gibs.peixunapi.model.StudyProgress;
import com.gibs.peixunapi.model.VideoClass;
import com.gibs.peixunapi.result.Result;
import com.gibs.peixunapi.service.StudyProgressService;
import com.gibs.peixunapi.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityNotFoundException;
import javax.validation.Valid;
import java.util.List;

@Service
@Slf4j
public class StudyProgressServiceImpl implements StudyProgressService {

    @Autowired
    private StudyProgressDao studyProgressDao;
    @Autowired
    private ExercisesDao exercisesDao;
    @Autowired
    private ExerciseRecordDao recordDao;
    @Autowired
    private VideoClassDao videoClassDao;
    @Autowired
    private DocumentationDao documentationDao;
    @Autowired
    private UserDao userDao;

    @Transactional
    @Override
    public Result create(@Valid StudyProgress object) {
        try {

//			objectDao.save(object);
            return ResultUtil.success(ResultEnum.CREATE_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Transactional
    @Override
    public Result save(@Valid StudyProgress object) {
        try {

//			StudyProgress studyProgress = objectDao.findOne(object.getId());
//			ConverterUtil.copyNotNullProperties(object,studyProgress);
//			objectDao.save(studyProgress);
            return ResultUtil.success(ResultEnum.UPDATE_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result delete(Integer id) {
        try {
//			String[] ids = id.split(",");
//			for (String str : ids) {
//				objectDao.delete(Integer.valueOf(str));
//			}
            return ResultUtil.success(ResultEnum.DELETE_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }


    @Override
    public Result get(Integer id) {
        try {
//			HashMap<String, Object> data = new HashMap<String, Object>();
//			StudyProgress object = objectDao.findOne(id);
//			if (object == null) {
//				Result(false, Status.FAILD, "查找失败", null);
//			}
//			HashMap<String,Object> map = new HashMap();
//			map.put("id", object.getId());
//			HashMap<String,Object> studentId = new HashMap<String,Object>();
//			studentId.put("name", object.getStudentId()==null?"":object.getStudentId().getName());
//			studentId.put("id", object.getStudentId()==null?"":object.getStudentId().getId());
//			map.put("studentId", studentId);
//			HashMap<String,Object> lessonId = new HashMap<String,Object>();
//			lessonId.put("name", object.getLessonId()==null?"":object.getLessonId().getName());
//			lessonId.put("id", object.getLessonId()==null?"":object.getLessonId().getId());
//			map.put("lessonId", lessonId);
//			HashMap<String,Object> chapterId = new HashMap<String,Object>();
//			chapterId.put("name", object.getChapterId()==null?"":object.getChapterId().getName());
//			chapterId.put("id", object.getChapterId()==null?"":object.getChapterId().getId());
//			map.put("chapterId", chapterId);
//			map.put("progress", object.getProgress()==null?"":object.getProgress());
//			HashMap<String,Object> vodioProgress = new HashMap<String,Object>();
//			vodioProgress.put("name", object.getVodioProgress()==null?"":object.getVodioProgress().getName());
//			vodioProgress.put("id", object.getVodioProgress()==null?"":object.getVodioProgress().getId());
//			map.put("vodioProgress", vodioProgress);
//			map.put("exerciseProgress", object.getExerciseProgress()==null?"":object.getExerciseProgress());
//			data.put("object",map);

            return ResultUtil.success(ResultEnum.FIND_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result getList(String key) {
        try {
//			List<StudyProgress> list = new ArrayList<>();
//			if (!StringUtils.isEmpty(key)) {
//				list = objectDao.findLike("%" + key + "%");
//			} else {
//				list = objectDao.findAll();
//			}
//			if (list.size() == 0) {
//				PageResult(true, Status.OK, "无数据", new ArrayList(), 0L,0,0);
//			}
//			List<Object> data = new ArrayList<>();
//			for(StudyProgress object : list){
//				HashMap<String,Object> map = new HashMap();
//				map.put("id", object.getId());
//				HashMap<String,Object> studentId = new HashMap<String,Object>();
//				studentId.put("name", object.getStudentId()==null?"":object.getStudentId().getName());
//				studentId.put("id", object.getStudentId()==null?"":object.getStudentId().getId());
//				map.put("studentId", studentId);
//				HashMap<String,Object> lessonId = new HashMap<String,Object>();
//				lessonId.put("name", object.getLessonId()==null?"":object.getLessonId().getName());
//				lessonId.put("id", object.getLessonId()==null?"":object.getLessonId().getId());
//				map.put("lessonId", lessonId);
//				HashMap<String,Object> chapterId = new HashMap<String,Object>();
//				chapterId.put("name", object.getChapterId()==null?"":object.getChapterId().getName());
//				chapterId.put("id", object.getChapterId()==null?"":object.getChapterId().getId());
//				map.put("chapterId", chapterId);
//				map.put("progress", object.getProgress()==null?"":object.getProgress());
//				HashMap<String,Object> vodioProgress = new HashMap<String,Object>();
//				vodioProgress.put("name", object.getVodioProgress()==null?"":object.getVodioProgress().getName());
//				vodioProgress.put("id", object.getVodioProgress()==null?"":object.getVodioProgress().getId());
//				map.put("vodioProgress", vodioProgress);
//				map.put("exerciseProgress", object.getExerciseProgress()==null?"":object.getExerciseProgress());
//				data.add(map);
//			}
            return ResultUtil.success(ResultEnum.FIND_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result getListPage(String key, Integer current, Integer limit) {
        try {
//			List<StudyProgress> list = new ArrayList<>();
//			limit = limit == null ? 10 : limit;
//			current = current == null ? 1 : current;
//			int offset = (current - 1) * limit;
//			Long total = null;
//			if (!StringUtils.isEmpty(key)) {
//				list = objectDao.findPageLike("%" + key + "%", offset, limit);
//				total = objectDao.countLike("%" + key + "%");
//			} else {
//				list = objectDao.findPage(offset, limit);
//				total = objectDao.count();
//			}
//			if (total == 0) {
//				PageResult(true, Status.OK, "无数据", new ArrayList(), 0L,0,0);
//			}
//			List<Object> data = new ArrayList<>();
//			for(StudyProgress object : list){
//				HashMap<String,Object> map = new HashMap();
//				map.put("id", object.getId());
//				HashMap<String,Object> studentId = new HashMap<String,Object>();
//				studentId.put("name", object.getStudentId()==null?"":object.getStudentId().getName());
//				studentId.put("id", object.getStudentId()==null?"":object.getStudentId().getId());
//				map.put("studentId", studentId);
//				HashMap<String,Object> lessonId = new HashMap<String,Object>();
//				lessonId.put("name", object.getLessonId()==null?"":object.getLessonId().getName());
//				lessonId.put("id", object.getLessonId()==null?"":object.getLessonId().getId());
//				map.put("lessonId", lessonId);
//				HashMap<String,Object> chapterId = new HashMap<String,Object>();
//				chapterId.put("name", object.getChapterId()==null?"":object.getChapterId().getName());
//				chapterId.put("id", object.getChapterId()==null?"":object.getChapterId().getId());
//				map.put("chapterId", chapterId);
//				map.put("progress", object.getProgress()==null?"":object.getProgress());
//				HashMap<String,Object> vodioProgress = new HashMap<String,Object>();
//				vodioProgress.put("name", object.getVodioProgress()==null?"":object.getVodioProgress().getName());
//				vodioProgress.put("id", object.getVodioProgress()==null?"":object.getVodioProgress().getId());
//				map.put("vodioProgress", vodioProgress);
//				map.put("exerciseProgress", object.getExerciseProgress()==null?"":object.getExerciseProgress());
//				data.add(map);
//			}
//			PageData pageData = new PageData(total, limit, current);
            return ResultUtil.successPage(ResultEnum.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }


    @Override
    public Result getOptions(String key) {
        try {
//			List<StudyProgress> list = new ArrayList<>();
//			if (!StringUtils.isEmpty(key)) {
//				list = objectDao.findLike("%" + key + "%");
//			} else {
//				list = objectDao.findAll();
//			}
//			List<Object> data = new ArrayList<>();
//			for (StudyProgress object : list) {
//				HashMap<String, Object> map = new HashMap();
//				map.put("value", object.getId());
//				map.put("name", object.getStudentId());
//				data.add(map);
//			}
            return ResultUtil.success(ResultEnum.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result saveProgress(Integer studentId, List<StudyRecordVO> recordVOList) {
        //1判断章节类型
        Exercises exercises = exercisesDao.findById(recordVOList.get(0).getExerciseId()).orElseThrow(EntityExistsException::new);
        StudyProgress studyProgress = new StudyProgress();

        if (exercises.getDocumentation() != null) {
            //文档选择saveDocumentProgress()
            studyProgress = saveDocumentProgress(studentId, exercises);
        } else {
            //视频选择saveVideoProgress()
            studyProgress = saveVideoProgress(studentId,exercises, recordVOList);
        }
        studyProgress.setStudent(userDao.findById(studentId).orElseThrow(EntityExistsException::new));
        studyProgressDao.save(studyProgress);
        return ResultUtil.success(ResultEnum.UPDATE_SUCCESS);
    }

    private StudyProgress saveDocumentProgress(Integer studentId, Exercises exercises) {
        //1.获取该章节练习题个数
        Integer countExercise = exercisesDao.countExercisesByDocumentation(exercises.getDocumentation());
        if (countExercise < 1) {
            throw new BaseException(ResultEnum.DATA_NOT_FIND);
        }
        //获取该学生在此章节的习题记录个数
        Integer countRecord = recordDao.countExerciseRecordsByStudent_IdAndExercise_Id(studentId, exercises.getId());
        //计算进度
        Double progress = countRecord.doubleValue() / countExercise.doubleValue();

        StudyProgress studyProgress = new StudyProgress();
        studyProgress.setDocumentation(documentationDao.findById(exercises.getDocumentation()).orElseThrow(EntityNotFoundException::new));
        studyProgress.setProgress(progress);

        return studyProgress;
    }

    private StudyProgress saveVideoProgress(Integer studentId, Exercises exercises, List<StudyRecordVO> recordVOList) {
        //获取该章节的视频时长
        Exercises exercise = exercisesDao.findById(exercises.getId()).orElseThrow(EntityNotFoundException::new);
        VideoClass videoClass = videoClassDao.findById(exercise.getVideoClass()).orElseThrow(EntityNotFoundException::new);
        Integer time = videoClass.getVideo().getDuration();
        //获取此学生在此章节的视频最长已看时长记录
        Integer newCountTime = recordVOList.get(0).getTimeRecord();
        Integer oldCountTime = studyProgressDao.findTimeRecord(videoClass.getId(),studentId);
        int countTime = Math.max(newCountTime, oldCountTime);
        //计算进度
        Double progress = (double) countTime / time.doubleValue();

        StudyProgress studyProgress = new StudyProgress();
        studyProgress.setVideoClass(videoClass);
        studyProgress.setProgress(progress);

        return studyProgress;
    }

    @Override
    public Result getVideoClassProgress(Integer studentId, Integer videoClassId) {
        StudyProgress studyProgress = studyProgressDao.findByVideoClass_IdAndStudent_Id(videoClassId,studentId);
        if (studyProgress == null) {
            throw new BaseException(ResultEnum.DATA_NOT_FIND);
        }
        return ResultUtil.success(ResultEnum.FIND_SUCCESS, studyProgress.getTimeRecord());
    }
}

